package util

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/s3"

	"net/http"
	"regexp"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"

	"mindonmap/pkgs/setting"
)

func GetPage(c *gin.Context) int {
	result := 0
	page, _ := com.StrTo(c.Query("page")).Int()
	if page > 0 {
		result = (page - 1) * setting.PageSize
	}

	return result
}

// 存 R2
func WriteFile(acid string, Mindid string, base64_image_content string) string {
	b, err := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, base64_image_content)
	if !b {
		return ""
	}
	if err != nil {
		return ""
	}
	re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`)
	allData := re.FindAllSubmatch([]byte(base64_image_content), 2)

	fileType := string(allData[0][1]) //png ，jpeg 后缀获取
	base64Str := re.ReplaceAllString(base64_image_content, "")

	now := time.Now()
	filepath := now.Format("2006-01-02")
	var Filename = filepath + "/" + "111" + "preview/" + Mindid + "." + fileType

	buffer, _ := base64.StdEncoding.DecodeString(base64Str)
	buffers := bytes.NewBuffer(buffer)

	var size = int64(buffers.Len())

	var aws3 = setting.GetAWSS3()
	AccessKeyID := aws3.AccessKeyID
	SecretAccessKey := aws3.SecretAccessKey
	S3Bucket := aws3.S3Bucket
	AccountId := aws3.AccountId

	creds := credentials.NewStaticCredentialsProvider(AccessKeyID, SecretAccessKey, "")

	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(creds),
		config.WithRegion("auto"), // Cloudflare R2 doesn't use regions, but this is required by the SDK
	)
	if err != nil {
		fmt.Println(err)
	}
	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.BaseEndpoint = aws.String(fmt.Sprintf("https://%s.r2.cloudflarestorage.com", AccountId))
	})
	_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket:             aws.String(S3Bucket),
		Key:                aws.String(Filename),
		ACL:                "public-read",
		Body:               bytes.NewReader(buffer),
		ContentLength:      aws.Int64(size),
		ContentType:        aws.String(http.DetectContentType(buffer)),
		ContentDisposition: aws.String("attachment"),
	})
	if err != nil {
		fmt.Println(err)
	}

	imageurl := "/" + Filename
	return imageurl
}

// 通用验证函数
func IsValidJSON(data []byte) bool {
	return json.Valid(data)
}

// 存 R2
func WriteTxt(acid string, Mindid string, jsonData map[string]interface{}) string {

	buffer, err := json.Marshal(jsonData)
	if err != nil {
		fmt.Println("JSON 编码出错:", err)
		return ""
	}

	now := time.Now()
	filepath := now.Format("2006-01-02")
	var Filename = filepath + "/" + acid + "preview/" + Mindid + "." + "txt"
	size := int64(len(buffer))
	var aws3 = setting.GetAWSS3()
	AccessKeyID := aws3.AccessKeyID
	SecretAccessKey := aws3.SecretAccessKey
	S3Bucket := aws3.S3Bucket
	AccountId := aws3.AccountId

	creds := credentials.NewStaticCredentialsProvider(AccessKeyID, SecretAccessKey, "")

	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(creds),
		config.WithRegion("auto"), // Cloudflare R2 doesn't use regions, but this is required by the SDK
	)
	if err != nil {
		fmt.Println(err)
	}
	client := s3.NewFromConfig(cfg, func(o *s3.Options) {
		o.BaseEndpoint = aws.String(fmt.Sprintf("https://%s.r2.cloudflarestorage.com", AccountId))
	})
	_, err = client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket:             aws.String(S3Bucket),
		Key:                aws.String(Filename),
		ACL:                "public-read",
		Body:               bytes.NewReader(buffer),
		ContentLength:      aws.Int64(size),
		ContentType:        aws.String("text/plain"),
		ContentDisposition: aws.String("attachment"),
	})
	if err != nil {
		fmt.Println(err)
	}

	imageurl := "/" + Filename
	return imageurl
}
